import { Router } from 'vue-router'
import { Toast, Notify } from 'vant'
import { useUserStore } from '@/store/user'
import { getToken, blackList } from './auth'

export function routerPersion(router: Router) {
  const store = useUserStore()
  router.beforeEach(async (to: any, from: any, next: any) => {
    // 设置标题
    document.title = to.meta.title || '魏州街道办智慧防疫'

    if (blackList.includes(to.path)) {
      // 白名单没有token也直接放行
      next()
      return
    }
    if (to.path.indexOf('login') > 0) {
      next()
      return
    }
    // 根据token判断用户是否登录
    const hasToken = getToken()
    if (hasToken) {
      if (to.path === '/') {
        // 如果已经登录了，而去的又是login页就重定向到首页
        next({ path: '/home' })
      } else {
        const hasUserInfo = store.uid
        if (hasUserInfo) {
          next()
        } else {
          // 如果用户刷新了浏览器，那么需要重新请求基本信息塞到vuex中进行状态管理
          try {
            await store.getUserInfo()
            next()
          } catch (error) {
            // 清空token重新去登录
            store.logout()
            Toast.fail('出错了')
            next(`/login?redirect=${encodeURI(location.href)}`)
          }
        }
      }
    } else {
      Notify({ type: 'primary', message: '请先登录后再操作' })
      // next(`/login?redirect=${to.fullPath}`)
      //测试环境
      // window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxac83e71a9371c1b4&redirect_uri=https%3A%2F%2Ffangyi.kaizhuoyun.com%2Fsapi%2Fwechat&response_type=code&scope=snsapi_base&state=jdb#wechat_redirect';
      //生产环境
      window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc4e528e68398e56e&redirect_uri=https%3A%2F%2Fjdb.kaizhuoyun.com%2Fsapi%2Fwechat&response_type=code&scope=snsapi_base&state=jdb#wechat_redirect';
    }
  })
}
